package com.leyou.mq;

import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import com.leyou.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author: Rose
 * @Date: 2021/4/9 13:12
 * @description ${description}
 * @version: 1.0.0
 */
@Slf4j
@EnableConfigurationProperties(SmsProperties.class)
@Component
public class SmsListener {


    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties props;


    /**
     * 发送短信验证码
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sms.verify.code.queue", durable = "true"),
            exchange = @Exchange(name = "ly.sms.exchange", type = ExchangeTypes.TOPIC),
            key = {"sms.verify.code"}
    ))
    public void listenSms(Map<String, String> msg) {

        if (CollectionUtils.isEmpty(msg)) {
            return;
        }
        log.info("接收到的短信数据为:{}", JsonUtils.tostring(msg));
        String phoneNumber = msg.remove("phone");
        if (StringUtils.isEmpty(phoneNumber)) {
            return;
        }

        // 处理消息, 失败不要重试， 容易触发 短信的限流， 限制账号的短信发送功能
        smsUtils.sendSms(phoneNumber, props.getSignName(), props.getVerifyCodeTemplate(), JsonUtils.tostring(msg));


    }

}
